﻿using System;
using System.IO;
using SDCloudSolution.SDCloud.BusinessLayer.Interfaces;

namespace SDCloudSolution.SDCloud.BusinessLayer
{
    public class FileStorageProvider : IFileStorageProvider
    {
        private readonly IFileStorageSettingsProvider _fileStorageSettingsProvider;

        public FileStorageProvider(IFileStorageSettingsProvider fileStorageSettingsProvider)
        {
            _fileStorageSettingsProvider = fileStorageSettingsProvider;
        }

        public Stream GetFile(string relatedPath)
        {
            var fullPath = GetFullFilePath(relatedPath);

            if (!File.Exists(fullPath))
            {
                return null;
            }

            return new FileStream(fullPath, FileMode.Open);
        }

        public void UploadFile(string relatedPath, Stream inputStream)
        {
            if (string.IsNullOrWhiteSpace(relatedPath))
            {
                throw new ArgumentNullException(relatedPath);
            }

            if (inputStream == null)
            {
                throw new ArgumentNullException("inputStream");
            }

            // TODO Security: Validate related path

            var fullPath = GetFullFilePath(relatedPath);

            var directoryName = Path.GetDirectoryName(fullPath);
            if (directoryName != null && !Directory.Exists(directoryName))
            {
                Directory.CreateDirectory(directoryName);
            }

            using (var outputStream = File.Create(fullPath))
            {
                inputStream.Seek(0, SeekOrigin.Begin);
                inputStream.CopyTo(outputStream);
            }
        }

        public void DeleteFile(string relatedPath)
        {
            if (string.IsNullOrWhiteSpace(relatedPath))
            {
                throw new ArgumentNullException("relatedPath");
            }

            var fullPath = GetFullFilePath(relatedPath);
            if (File.Exists(fullPath))
            {
                File.Delete(fullPath);
            }
        }

        public string GetFullFilePath(string relatedPath)
        {
            return Path.Combine(_fileStorageSettingsProvider.FileStorageBasePath, relatedPath);
        }
    }
}